package com.jcroke.PC32.serialize;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.LinkedHashMap;

import com.jcroke.DACGraph.Pnode;
import com.jcroke.PC32.basetransform.DefaultTransformer;
import com.jcroke.PC32.datum.Datum;

/**
 * 
 * @author jcroke
 *
 */
public class SimpleDelimiterSerializer extends DefaultTransformer {

	// Input tags
	public final String DELIM = "serializer_arg0_in";
	public final String ORDERED_TAG_NAMES_IN = "orderedTagNames_in";

	private LinkedHashMap<String, Datum> input;
	private String[] tags;

	@Override
	public void prepare(Pnode pnode) {
		super.prepare(pnode);
		input = getInput();
		// Get the ordered tags
		String inputTagList = input.get(ORDERED_TAG_NAMES_IN).toString();
		tags = inputTagList.split("\\s*,\\s*");
	}

	public void execute() {

		String delim = input.get(DELIM).toString();
		BufferedWriter bw = pNode().getBoWriter();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < tags.length; i++) {
			sb.append(input.get(tags[i]).toString());
			sb.append((i + 1 < tags.length) ? delim : "");
		}
		try {
			bw.write(sb.toString());
			bw.write("\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
